


let {Matrix4,Vector3} = require('../math');
let Transform = require('./Transform');

let _dir = new Vector3();

class Camera{
    constructor(){
        this._transform = new Transform();
        this._viewMatrix = new Matrix4();
        this._projMatrix = null;
    }

    getTransform(){
        return this._transform;
    }

    setProj(fov,aspect,near,far){
        if (!this._projMatrix){
            this._projMatrix = new Matrix4();
        }
        this._projMatrix.perspective(fov,aspect,near,far);
    }

    updateCamera() {
         this._transform.updateMatrix();
         this._viewMatrix.getInverse(this._transform.getWorldMatrix());
         return this;
    }

    getViewMatrix(){
        return this._viewMatrix;
    }

    getProjMatrix(){
        return this._projMatrix;
    }

    //-------------
    forward(scalar,bFly= false){
        // 朝dir方向前进
        let dir = this._transform.getDir(_dir);
        dir.multiplyScalar(scalar);
        if (!bFly){
            dir.y = 0;
        }
        let pos = this._transform.getPosition();
        this._transform.setPosition(pos.x + dir.x,pos.y + dir.y,pos.z + dir.z);
        this.updateCamera();
    }
    right(scalar){
        // 朝 相机自己 +x 轴移动
        let worldMatrix = this._transform.getWorldMatrix();
        let xAxis = _dir.setFromMatrixColumn(worldMatrix,0);
        xAxis.multiplyScalar(scalar);
        let pos = this._transform.getPosition();
        this._transform.setPosition(pos.x + xAxis.x,pos.y + xAxis.y,pos.z + xAxis.z);
        this.updateCamera();
    }
}

module.exports = Camera;
